package complete;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

import static complete.JwtUtil.USER_NAME;


/*
    https://auth0.com/blog/securing-spring-boot-with-jwts/
	https://github.com/auth0-blog/spring-boot-jwts
	https://github.com/szerhusenBC/jwt-spring-security-demo
*/

@SpringBootApplication
@RestController
public class Application {

	public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
	
    @PostMapping("/login")
    public Object login(HttpServletResponse response, @RequestBody final Account account) throws IOException {
    	if("admin".equals(account.username) && "admin".equals(account.password)) {
        	HashMap<String, String> map = new HashMap<String,String>();
        	map.put("token", JwtUtil.generateToken(account.username));
        	return map;
        }else {
            return new ResponseEntity<Object>(HttpStatus.UNAUTHORIZED);
        }
    }
    
    @GetMapping("/api/protected")
    public @ResponseBody
    Object hellWorld(@RequestHeader(value = USER_NAME) String userId) {
        return "Your user id is '" + userId + "'";
    }

    
    @Bean
    public FilterRegistrationBean jwtFilter() {
    	 final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
         registrationBean.setFilter(new JwtAuthenticationFilter());
         return registrationBean;
    }


    public static class Account {
        public String username;
        public String password;
    }

   
}